package services;

import entities.Article;
import forms.ArticleForm;
import helpers.IdUniqueHelper;
import helpers.NumberHelper;

import java.io.IOException;
import java.util.Map;
import java.util.TreeMap;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import models.ArticleModel;
import systems.Recently;
import systems.RecentlyTag;

@SuppressWarnings("serial")
public class SubmitArticleService extends HttpServlet {
	
	private static final Logger log = Logger.getLogger(SubmitArticleService.class.getName());
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		
		//submitArticle(response);
		
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		
		response.setContentType("text/html");
		
		ArticleModel articleModel = ArticleModel.getInstance();
		Article article = new Article();
		
		TreeMap form = ArticleForm.checkValidSubmitService(request, article);
		TreeMap<String, String> check = (TreeMap<String, String>) form.get("checkValid");
		article = (Article) form.get("article");
		
		if (check.size() == 0) {
			//Check submitStatus config
			article.setStatus(1);
			
			article.setId(IdUniqueHelper.getId());
			article.setRate(NumberHelper.getRandomNumberFrom(2, 5));
			article.setAuthKey(IdUniqueHelper.getId());
			articleModel.insert(article);
			//ArticleDebug.debug(article);
			
			//Update tag
			RecentlyTag.insert(article.getKeywords());
			
			//Update recently Cache
			if (article.getStatus() == 1) {
				Recently.update(article);
			}
			
			response.getWriter().println("Submit article success with id " + article.getId());
			log.warning("Submit success");
		} else {
			for (Map.Entry<String,String> entry : check.entrySet()) {
		        log.warning(entry.getKey() + " => " + entry.getValue());
		    }
		}
		
	}
	
	private void submitArticle(HttpServletResponse response) {
		
		String url = "http://localhost:8888/service/submit-article";
		
		try {
			String title = "article 4";
			String content = "By using videos you can fascinate your audience by showing them realistic facts of business and impress with diverse striking ways.";
			String category = "5G24GQIM";
			String name = "hoanbn";
			String email = "hoantocxoan@gmail.com";
			String website = "http://www.google.com";
			String keywords = "article3, keyword3";
			String sl = "en";
			String tl = "es";
			
			Connection conn = Jsoup.connect(url);
			Document doc = conn
				.header("accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
				.header("accept-Language", "en-us,en;q=0.5")
				//.header("host", "www.webpagetest.org")
				//.header("referer", "http://www.webpagetest.org/")
				//.cookie("o",response.cookie("o"))
				.userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:15.0) Gecko/20100101 Firefox/15.0.1")
				.data("title", title)
				.data("content", content)
				.data("category",category)
				.data("name",name)
				.data("email",email)
				.data("website",website)
				.data("keywords",keywords)
				.data("sl", sl)
				.data("tl", tl)
				.followRedirects(false)
				.post();
			
			response.getWriter().println(doc.html());
			
		} catch (Exception e) {
			e.printStackTrace();
			// TODO: handle exception
		}
	}
}
